<template>
  <div class="robot-config" v-loading="loading">
    <!-- 机器人功能配置说明 -->
    <el-card class="card-box">
      <template #header>
        <span class="style-text">机器人功能配置说明 </span>
      </template>
      <el-steps :active="3" align-center class="w-full">
        <el-step title="机器人设置" description="当前页面" />
        <el-step title="知识库设置">
          <template #description>
            前往设置： <el-button type="primary" link @click="toSetting">设置</el-button>
          </template>
        </el-step>
        <el-step title="设置完成" description="机器人功能可以使用" />
      </el-steps>
    </el-card>

    <!-- 机器人名片 -->
    <el-card class="card-box">
      <template #header>
        <span class="style-text">机器人名片 </span>
        <el-row class="full w-ful">
          <el-col :span="22" class="tips">顾客在网站和SDK等对话窗口会看到的客服消息</el-col>
          <el-col :span="2"
            ><el-button type="primary" link @click="handleEdit">编辑</el-button></el-col
          >
        </el-row>
      </template>
      <div class="card" v-if="isEditSettingVisiable">
        <el-upload
          class="avatar-uploader"
          action="http://api.kefu.xurj.top/image/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          accept="image/jpeg,image/jpg,image/png,image/webp"
        >
          <img v-if="robot.avatar" :src="robot.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>

        <el-input v-model="robot.name" type="text" @keyup.enter="handleEditRobot" />
      </div>
      <div class="card" v-else>
        <img :src="robot.avatar" alt="机器人头像" @click="showMessage" />
        <span>{{ robot.name }}</span>
      </div>
    </el-card>

    <!-- 机器人欢迎语 -->
    <el-card class="card-box">
      <template #header>
        <span class="style-text">机器人欢迎语 </span>
        <el-row class="full w-ful">
          <el-col :span="22" class="tips">每段对话开启时，系统自动向客户发送一段欢迎语</el-col>
          <el-col :span="2"
            ><el-button type="primary" link @click="handleMessage">编辑</el-button></el-col
          >
        </el-row>
      </template>
      <div class="card" v-if="isEditMessage" style="flex-direction: column; align-items: flex-end">
        <div style="border: 1px solid gray" class="wangeditor w-full">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            mode="simple"
          />
          <Editor
            class="editor-content"
            style="height: 300px; overflow-y: hidden"
            v-model="robot.greeting"
            :defaultConfig="editorConfig"
            mode="simple"
            @onCreated="handleCreated"
          />
        </div>

        <el-button
          type="primary"
          @click="handleSubmitMessage"
          style="text-align: right; margin: 10px 0"
          >提交</el-button
        >
      </div>
      <div class="card" v-else>
        <div v-html="robot.greeting"></div>
      </div>
    </el-card>

    <!-- 转人工配置 -->
    <el-card class="card-box">
      <template #header>
        <span class="style-text">转人工配置 </span>
        <el-row class="full w-ful">
          <el-col :span="22" class="tips">机器人对话转人工相关配置</el-col>
        </el-row>
      </template>
      <div class="card w-full">
        <el-row flex class="flex w-full style-row">
          <el-col :span="12" style="display: inline-flex; align-items: center">
            <div class="title" style="padding-right: 10px">机器人转人工按钮</div>
            <el-switch v-model="robot.showManual" @change="handleChanegSwitch" />
          </el-col>
        </el-row>
        <el-row flex class="flex w-full style-row">
          <el-col :span="12" style="display: inline-flex; align-items: center">
            <div class="title" style="padding-right: 10px">机器人未识别转人工</div>
            <el-button type="primary" link @click="toSettingRobot">前往设置</el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-dialog title="机器人未识别转人工设置" v-model="toSettingVisible" width="70%" height="600px">
      <div style="height: 400px; overflow-y: auto">
        <el-form
          :model="robot"
          ref="formRef"
          label-width="120px"
          label-position="top"
          :rules="rules"
        >
          <el-form-item label="">
            <p>当机器人没能回答出客户提出的问题，可帮助机器人进行回答</p>
          </el-form-item>
          <el-form-item label="">
            <el-row class="w-full">
              <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                <span style="padding-right: 10px">转入设置</span>
                <el-select
                  v-model="robot.unrecognizedCout"
                  placeholder="请选择"
                  style="width: 100px"
                >
                  <el-option v-for="item in timesOptions" :key="item" :label="item" :value="item" />
                </el-select>
                <span style="padding-left: 10px">次后</span>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                <el-select v-model="robot.toManualType" placeholder="请选择" style="width: 100px">
                  <el-option
                    v-for="item in transferOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>

                <span style="padding-left: 10px">转人工</span>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item
            v-for="(item, index) in robot.replyContent"
            :key="index"
            :label="`第${item.sort}次未识别`"
            :prop="`replyContent[${index}].content`"
          >
            <el-input type="textarea" v-model="item.content" />
          </el-form-item>

          <!-- <el-form-item label="第2次未识别" prop="replyContent[1].content">
          <el-input type="textarea" v-model="robot.replyContent[1].content" />
        </el-form-item> -->

          <el-form-item label="手动转人工文本" prop="manualContent">
            <el-input type="textarea" v-model="robot.manualContent" />
          </el-form-item>

          <el-form-item label="当前无在线客服引导文本" prop="noOnlineContent">
            <el-input type="textarea" v-model="robot.noOnlineContent" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span>
          <el-button @click="toSettingVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, shallowRef, onBeforeUnmount } from "vue";
import { ElButton, ElInput, ElSwitch } from "element-plus";
import { robotSeeting, robotGetInfo, unrecognizedReplySetting } from "@/api/node-admin-api/robot";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { successMessage, warnMessage, errorMessage } from "@/utils/message";
import "@wangeditor/editor/dist/css/style.css";

const emit = defineEmits(["toSetting"]);
const robotName = ref("机器人名称");
const welcomeMessage = ref("欢迎使用我们的服务！");
const manualTransferEnabled = ref(false);

const loading = ref(false);

onMounted(() => {
  getRotbot();
});

const robot = ref({
  avatar: "",
  greeting: "",
  name: "",
  showManual: false,
  unrecognizedCout: 3,
  toManualType: 0,
  replyContent: [],
  manualContent: "不太懂你说什么，是否需要转接人工？",
  noOnlineContent: "当前无人在线客服，您可以继续当前机器人对话或其他时段再咨询，谢谢",
});

const initializeReplyContent = () => {
  const currentCount = robot.value.unrecognizedCout;
  const existingLength = robot.value.replyContent.length;

  if (currentCount > existingLength) {
    // 如果需要的数量比现有的多，添加新的元素
    for (let i = existingLength; i < currentCount; i++) {
      robot.value.replyContent.push({
        content: ``,
        sort: i + 1,
      });
    }
  } else if (currentCount < existingLength) {
    // 如果需要的数量比现有的少，移除多余的元素
    robot.value.replyContent.splice(currentCount);
  }
  // 如果数量相等，不做任何操作
};

// 监听 unrecognizedCout 的变化
watch(() => robot.value.unrecognizedCout, initializeReplyContent, { immediate: true });

const getRotbot = () => {
  loading.value = true;
  robotGetInfo()
    .then((res) => {
      if (res.code == 20000) {
        robot.value = { ...res.data.robot, replyContent: res.data.replys };
      }
    })
    .finally((res) => {
      loading.value = false;
    });
};
const showMessage = () => {
  successMessage("请先点击右侧编辑按钮再点击头像更改");
};
// 编辑机器人设置
const handleEditRobot = (params) => {
  loading.value = true;
  robotSeeting({ ...robot.value, ...params })
    .then((res) => {
      if (res.code == 20000) {
        getRotbot();
      } else {
        errorMessage(res.message);
      }
    })
    .finally((res) => {
      loading.value = false;
      isEditSettingVisiable.value = false;
      isEditMessage.value = false;
    });
};

const handleChanegSwitch = (val) => {
  const params = { ...robot.value, showManual: val };
  handleEditRobot(params);
};

const editRobotCard = () => {
  // 编辑机器人名片逻辑
  handleEditRobot();
};

const editWelcomeMessage = () => {
  // 编辑欢迎语逻辑
  handleEditRobot();
};

const toSetting = () => {
  emit("toSetting");
};

const isEditSettingVisiable = ref(false);
const handleEdit = () => {
  isEditSettingVisiable.value = true;
};

// 上传成功后
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 20000) {
    robot.value.avatar = response.data.url;
    handleEditRobot();
  } else {
    errorMessage("上传头像，请稍后再试");
  }
};

// 上传头像前控制
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    errorMessage("上传头像要求是 JPG 格式的图片");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    errorMessage("上传图片大小不要超过 5M");
    return false;
  }
  return true;
};
const editorRef = shallowRef();

const isEditMessage = ref(false);
const toolbarConfig = {
  toolbarKeys: [
    "clearStyle",
    "divider",
    "emotion",
    "blockquote",
    "|",
    // 菜单组，包含多个菜单
    {
      key: "group-link",
      title: "链接",
      menuKeys: ["insertLink", "editLink", "unLink", "viewLink"],
    },

    "redo",
    "undo",
  ],
};
const editorConfig = {
  placeholder: "请输入内容...",
  EXTEND_CONF: {
    mentionConfig: {
      pinyinSearch: true,
    },
  },
};
const handleMessage = () => {
  isEditMessage.value = true;
};

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const handleSubmitMessage = () => {
  handleEditRobot();
};
const formRef = ref(null);
const rules = ref({
  unrecognizedCout: [{ required: true, message: "请选择未识别次数", trigger: "change" }],
  toManualType: [{ required: true, message: "请选择转人工类型", trigger: "change" }],
  "replyContent[0].content": [
    { required: true, message: "请输入第1次未识别的回复内容", trigger: "blur" },
  ],
  "replyContent[1].content": [
    { required: true, message: "请输入第2次未识别的回复内容", trigger: "blur" },
  ],
  manualContent: [{ required: true, message: "请输入手动转人工文本", trigger: "blur" }],
  noOnlineContent: [{ required: true, message: "请输入无在线客服引导文本", trigger: "blur" }],
});

const toSettingVisible = ref(false);
const toSettingRobot = () => {
  toSettingVisible.value = true;
};

const timesOptions = Array.from({ length: 10 }, (v, i) => {
  return i + 1;
});

const transferOptions = [
  { value: 0, label: "自动" },
  { value: 1, label: "手动" },
];

const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const params = {
        rid: robot.value.id,
        ...robot.value,
      };
      unrecognizedReplySetting(params)
        .then((res) => {
          if (res.code == 20000) {
            successMessage("提交成功");
            getRotbot();
            toSettingVisible.value = false;
          }
        })
        .catch((res) => {
          errorMessage(res.message);
        });
    } else {
      errorMessage("表单验证失败，请检查输入");
      return false;
    }
  });
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style scoped lang="scss">
.robot-config {
  padding: 10px;
  height: 100%;
  overflow-y: auto;
  padding-top: 0;
  .card-box {
    margin-bottom: 20px;
    .tips {
      font-size: 14px;
      color: gray;
      padding-top: 10px;
    }
  }

  .card {
    img {
      border-radius: 100%;
    }
  }
}

.wangeditor {
  word-break: break-all;
  .editor-content {
    overflow-y: hidden;
    :deep(.w-e-text-container p) {
      margin: 0;
    }
    :deep(.w-e-image-dragger) {
      display: none;
    }
    :deep(.w-e-text-placeholder) {
      font-style: normal;
      font-size: 15px;
      top: 5px;
    }
    :deep(.w-e-selected-image-container) {
      overflow: visible;
    }
    :deep(.w-e-scroll) {
      @include scrollBar;
    }
  }
}
.robot-config .module {
  width: 100%;
  border-radius: 10px;
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ccc;
  .title {
    font-size: 18px;
    font-weight: bold;
    padding-top: 10px;
    padding-bottom: 20px;
  }
}
.robot-config .card {
  display: flex;
  align-items: center;
}
.robot-config img {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}
:deep(.el-step__head.is-finish) {
  border-color: var(--color-secondar);
}
:deep(.el-step__icon) {
  border-color: var(--color-highlight);
}
:deep(.el-step__icon-inner) {
  color: var(--color-highlight);
}
:deep(.el-step__title.is-finish) {
  color: var(--color-title);
}
:deep(.el-step.is-center .el-step__description) {
  color: var(--color-secondary);
}
</style>
